package slh.myMapReduce;

import java.io.IOException;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class TopRatedMovieMapper extends Mapper<LongWritable, Text, Text, FloatWritable> {

    private Text movieInfo = new Text();
    private FloatWritable movieScore = new FloatWritable();

    @Override
    public void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {

        // 输入格式: MOVIE_ID,TITLE,SCORE,RATING_COUNT
        String[] parts = value.toString().split(",");

        if (parts.length >= 3) {
            try {
                String movieId = parts[0].trim();
                String title = parts[1].trim();
                float score = Float.parseFloat(parts[2].trim());
                int ratingCount = parts.length > 3 ? Integer.parseInt(parts[3].trim()) : 0;

                // 只处理有足够评分的电影(避免评分人数过少的电影)
                if (ratingCount >= 10) { // 假设至少10人评分才计入统计
                    movieInfo.set(movieId + "|" + title); // 组合ID和标题
                    movieScore.set(score);
                    context.write(movieInfo, movieScore);
                }
            } catch (NumberFormatException e) {
                // 忽略格式错误的记录
            }
        }
    }
}
